package com.souku.finance.application.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.manager.RequestManager;
import com.souku.finance.application.R;
import com.souku.finance.application.base.ActivityManage;
import com.souku.finance.application.base.BaseFragmentActivity;
import com.souku.finance.application.bean.VersionBean;
import com.souku.finance.application.http.retrofit.RetrofitUtils;
import com.souku.finance.application.ui.borrow.BorrowFragment;
import com.souku.finance.application.ui.home.Home2Fragment;
import com.souku.finance.application.ui.login.LoginActivity;
import com.souku.finance.application.ui.mine.ExperienceTip2Activity;
import com.souku.finance.application.utils.Constant;
import com.souku.finance.application.http.UrlConstact;
import com.souku.finance.application.ui.lock.LockActivity;
import com.souku.finance.application.utils.level.MD5Util;
import com.souku.finance.application.utils.level.SystemUtils;
import com.souku.finance.application.widget.lock.MyKeyListener;
import com.souku.finance.application.ui.invite.InviteFragment;
import com.souku.finance.application.ui.mine.CheckinActivity;
import com.souku.finance.application.ui.mine.MineFragment;
import com.souku.finance.application.ui.more.MoreFragment;
import com.souku.finance.application.ui.more.NoticeActivity;
import com.souku.finance.application.utils.JsonUtil;
import com.souku.finance.application.utils.ParamUtil;
import com.souku.finance.application.utils.ShareUtil;
import com.souku.finance.application.utils.ToastUtil;
import com.souku.finance.application.http.volley.ReqListener;
import com.souku.finance.application.http.volley.Success;
import com.umeng.analytics.MobclickAgent;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends BaseFragmentActivity implements View.OnClickListener {

    protected ImageView topLeft;
    protected TextView topTitle;
    protected ImageView topRight;
    protected RelativeLayout idLlTop;
    protected LinearLayout idTabHome;
    protected LinearLayout idTabProduct;
    protected LinearLayout idTabPersonal;
    protected LinearLayout idTabMore;
    protected LinearLayout idTabBorrow;
    protected ImageView idTabHomeImg;
    protected ImageView idTabProductImg;
    protected ImageView idTabPersonalImg;
    protected ImageView idTabMoreImg;
    protected ImageView idTabBorrowImg;
    protected TextView tvHome;
    protected TextView tvTender;
    protected TextView tvMine;
    protected TextView tvMore;
    protected TextView tvBorrow;
    private Fragment mTab01;
    private Fragment mTab02;
    private Fragment mTab03;
    private Fragment mTab04;
    private Fragment mTab05;
    public static int page = 0;
    public static boolean islock = false;
    public static boolean isBackstage = false;
    public static Long lockTime = System.currentTimeMillis();

    public boolean isFirstStart = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_main);

        initView();

        //判断从未登录或者注册过，弹出体验金提示框
        if (!ShareUtil.getInstance().getBoolean(Constant.IsRegistered)) {
            Intent intent1 = new Intent(this, ExperienceTip2Activity.class);
            startActivity(intent1);
        }

        //判断登录并且设置过手势密码，就开启密码验证
        if (ShareUtil.getInstance().getBoolean(Constant.IsLogin) & ShareUtil.getInstance().getString(Constant.GesturePass) != null) {
//            Intent intent = new Intent(MainActivity.this, LockActivity.class);
//            startActivity(intent);
        }

        //程序启动
        ActivityManage.setRun(true);
        mTab01 = null;
        mTab02 = null;
        mTab03 = null;
        mTab04 = null;
        mTab05 = null;

        if (homeKeyListener == null) {
            homeKeyListener = new MyKeyListener(this);
            homeKeyStart(); //处理方法
            homeKeyListener.startHomeListener(); //开启监听
        }

        //开启服务器时间获取
//        handler.sendEmptyMessage(0);

    }

    public void getNewVersion() {
        RetrofitUtils.create().getNewVersion().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String json = response.body().string();
                    if (!TextUtils.isEmpty(json)) {
                        VersionBean versionBean = JsonUtil.fastBean(JsonUtil.getData(json).toString(), VersionBean.class);
                        String currentVersionCode = SystemUtils.getVersionCode(MainActivity.this);
                        if (versionBean.getVersionCode() > Integer.parseInt(currentVersionCode)) {
                            //有新版本
                            Intent intent = new Intent(MainActivity.this, VersionNewActivity.class);
                            startActivity(intent);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getNewestNoticeId();
        mainActivityToPage(page);
        if (isFirstStart && ShareUtil.getInstance().getBoolean(Constant.IsRegistered)) {
            getNewVersion();
            isFirstStart = false;
        }
    }

    public void mainActivityToPage(int i) {
        selectBottom(i);
        selectTop();
        page = i;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);
        if (i == 0) {
            if (mTab01 == null) {
                mTab01 = new Home2Fragment();
                transaction.add(R.id.id_content, mTab01);
            } else {
                transaction.show(mTab01);
            }
        } else if (i == 1) {
            if (mTab02 == null) {
                mTab02 = new InviteFragment();
                transaction.add(R.id.id_content, mTab02);
            } else {
                transaction.show(mTab02);
            }
        } else if (i == 2) {
            if (mTab03 == null) {
                mTab03 = new MineFragment();
                transaction.add(R.id.id_content, mTab03);
            } else {
                transaction.show(mTab03);
            }
        } else if (i == 3) {
            if (mTab04 == null) {
                mTab04 = new BorrowFragment();
                transaction.add(R.id.id_content, mTab04);
            } else {
                transaction.show(mTab04);
            }
        } else if (i == 4) {
            if (mTab05 == null) {
                mTab05 = new MoreFragment();
                transaction.add(R.id.id_content, mTab05);
            } else {
                transaction.show(mTab05);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    //隐藏全部fragment
    private void hideFragment(FragmentTransaction transaction) {

        if (mTab01 != null) {
            transaction.hide(mTab01);
        }
        if (mTab02 != null) {
            transaction.hide(mTab02);
        }
        if (mTab03 != null) {
            transaction.hide(mTab03);
        }
        if (mTab04 != null) {
            transaction.hide(mTab04);
        }
        if (mTab05 != null) {
            transaction.hide(mTab05);
        }
    }


    private MyKeyListener homeKeyListener;
    long waitTime = 2000;
    long touchTime = 0;

    //物理返回键按钮
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - touchTime) >= waitTime) {
                //让Toast的显示时间和等待时间相同
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                touchTime = currentTime;
            } else {
                isBackstage = true;
                startCount();
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * Home键开始监听
     */
    private void homeKeyStart() {

        homeKeyListener.setOnHomePressedListener(new MyKeyListener.OnHomePressedListener() {

            @Override
            public void onHomePressed() {
                isBackstage = true;
                startCount();
            }

            @Override
            public void onHomeLongPressed() {

            }

            @Override
            public void onScreenPressed() {

            }

            @Override
            public void offScreenPressed() {

            }
        });
    }

    //开始倒计30秒锁屏
    private void startCount() {
        if (!islock) {
            if (ShareUtil.getInstance().getBoolean(Constant.IsLogin) & ShareUtil.getInstance().getString(Constant.GesturePass) != null) {
                islock = true;
                lockTime = System.currentTimeMillis();
            }
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.id_tab_home) { //首页
            mainActivityToPage(0);
            MobclickAgent.onEvent(MainActivity.this, "home");

        } else if (view.getId() == R.id.id_tab_product) { //理财
            mainActivityToPage(1);
            MobclickAgent.onEvent(MainActivity.this, "manage");

        } else if (view.getId() == R.id.id_tab_personal) {   //我的
            mainActivityToPage(2);
            MobclickAgent.onEvent(MainActivity.this, "mine");

        } else if (view.getId() == R.id.id_tab_borrow) {  //借款
            mainActivityToPage(3);
            MobclickAgent.onEvent(MainActivity.this, "borrow");

        } else if (view.getId() == R.id.id_tab_more) {  //更多
            mainActivityToPage(4);
            MobclickAgent.onEvent(MainActivity.this, "more");

        } else if (view.getId() == R.id.top_right) { //公告
            Intent intent = new Intent(this, NoticeActivity.class);
            startActivity(intent);

        } else if (!ShareUtil.getInstance().getBoolean(Constant.IsLogin)) {//登录
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);

        } else if (view.getId() == R.id.top_left) { //签到
            Intent intent = new Intent(this, CheckinActivity.class);
            startActivity(intent);
        }
    }

    //底部选择切换
    private void selectBottom(int i) {
        switch (i) {
            case 0:
                topTitle.setText("首库金融");
                idTabHomeImg.setImageResource(R.drawable.home_icon_select);
                idTabProductImg.setImageResource(R.drawable.tender_icon);
                idTabPersonalImg.setImageResource(R.drawable.mine_icon);
                idTabBorrowImg.setImageResource(R.drawable.borrow_icon);
                idTabMoreImg.setImageResource(R.drawable.more_icon);
                tvHome.setTextColor(getResources().getColor(R.color.main));
                tvTender.setTextColor(getResources().getColor(R.color.black_text));
                tvMine.setTextColor(getResources().getColor(R.color.black_text));
                tvMore.setTextColor(getResources().getColor(R.color.black_text));
                tvBorrow.setTextColor(getResources().getColor(R.color.black_text));
                break;
            case 1:
                topTitle.setText("理财");
                idTabHomeImg.setImageResource(R.drawable.home_icon);
                idTabProductImg.setImageResource(R.drawable.tender_icon_select);
                idTabPersonalImg.setImageResource(R.drawable.mine_icon);
                idTabBorrowImg.setImageResource(R.drawable.borrow_icon);
                idTabMoreImg.setImageResource(R.drawable.more_icon);
                tvHome.setTextColor(getResources().getColor(R.color.black_text));
                tvTender.setTextColor(getResources().getColor(R.color.main));
                tvMine.setTextColor(getResources().getColor(R.color.black_text));
                tvMore.setTextColor(getResources().getColor(R.color.black_text));
                tvBorrow.setTextColor(getResources().getColor(R.color.black_text));
                break;
            case 2:
                topTitle.setText("我的");
                idTabHomeImg.setImageResource(R.drawable.home_icon);
                idTabProductImg.setImageResource(R.drawable.tender_icon);
                idTabPersonalImg.setImageResource(R.drawable.mine_icon_select);
                idTabBorrowImg.setImageResource(R.drawable.borrow_icon);
                idTabMoreImg.setImageResource(R.drawable.more_icon);
                tvHome.setTextColor(getResources().getColor(R.color.black_text));
                tvTender.setTextColor(getResources().getColor(R.color.black_text));
                tvMine.setTextColor(getResources().getColor(R.color.main));
                tvMore.setTextColor(getResources().getColor(R.color.black_text));
                tvBorrow.setTextColor(getResources().getColor(R.color.black_text));
                break;
            case 3:
                topTitle.setText("借款");
                idTabHomeImg.setImageResource(R.drawable.home_icon);
                idTabProductImg.setImageResource(R.drawable.tender_icon);
                idTabPersonalImg.setImageResource(R.drawable.mine_icon);
                idTabBorrowImg.setImageResource(R.drawable.borrow_icon_select);
                idTabMoreImg.setImageResource(R.drawable.more_icon);
                tvHome.setTextColor(getResources().getColor(R.color.black_text));
                tvTender.setTextColor(getResources().getColor(R.color.black_text));
                tvMine.setTextColor(getResources().getColor(R.color.black_text));
                tvBorrow.setTextColor(getResources().getColor(R.color.main));
                tvMore.setTextColor(getResources().getColor(R.color.black_text));
                break;
            case 4:
                topTitle.setText("更多");
                idTabHomeImg.setImageResource(R.drawable.home_icon);
                idTabProductImg.setImageResource(R.drawable.tender_icon);
                idTabPersonalImg.setImageResource(R.drawable.mine_icon);
                idTabBorrowImg.setImageResource(R.drawable.borrow_icon);
                idTabMoreImg.setImageResource(R.drawable.more_icon_select);
                tvHome.setTextColor(getResources().getColor(R.color.black_text));
                tvTender.setTextColor(getResources().getColor(R.color.black_text));
                tvMine.setTextColor(getResources().getColor(R.color.black_text));
                tvBorrow.setTextColor(getResources().getColor(R.color.black_text));
                tvMore.setTextColor(getResources().getColor(R.color.main));
                break;
        }
    }

    //顶部是否有公告的图标判断
    private boolean message = true;

    //获取最新公告id
    private void getNewestNoticeId() {
        HashMap<String, String> map = ParamUtil.getParams();
        RequestManager.getInstance().post(UrlConstact.NEWEST, ParamUtil.getSing(map), new ReqListener(this, new Success() {
            @Override
            public void onSuccess(String response) {
                if (JsonUtil.getCode(response) == 1) {
                    String id = JsonUtil.getString(JsonUtil.getData(response), "id");
                    String oldId = ShareUtil.getInstance().getString(Constant.NewestNoticeID);
                    if (oldId == null || !oldId.equals(id)) {
                        message = false;
                    } else {
                        message = true;
                    }
                    selectTop();
                } else {
                    ToastUtil.show(JsonUtil.getMessage(response));
                }
            }
        }), ParamUtil.getHeaders());
    }

    private void selectTop() {
        if (message) {
            topRight.setImageResource(R.drawable.mes);
        } else {
            topRight.setImageResource(R.drawable.mes);
        }
    }

    private void initView() {
        topLeft = (ImageView) findViewById(R.id.top_left);
        topLeft.setOnClickListener(MainActivity.this);
        topTitle = (TextView) findViewById(R.id.top_title);
        topRight = (ImageView) findViewById(R.id.top_right);
        topRight.setOnClickListener(MainActivity.this);
        idLlTop = (RelativeLayout) findViewById(R.id.id_ll_top);
        idTabHome = (LinearLayout) findViewById(R.id.id_tab_home);
        idTabHome.setOnClickListener(MainActivity.this);
        idTabProduct = (LinearLayout) findViewById(R.id.id_tab_product);
        idTabProduct.setOnClickListener(MainActivity.this);
        idTabPersonal = (LinearLayout) findViewById(R.id.id_tab_personal);
        idTabPersonal.setOnClickListener(MainActivity.this);
        idTabMore = (LinearLayout) findViewById(R.id.id_tab_more);
        idTabMore.setOnClickListener(MainActivity.this);
        idTabBorrow = (LinearLayout) findViewById(R.id.id_tab_borrow);
        idTabBorrow.setOnClickListener(MainActivity.this);
        idTabHomeImg = (ImageView) findViewById(R.id.id_tab_home_img);
        idTabProductImg = (ImageView) findViewById(R.id.id_tab_product_img);
        idTabPersonalImg = (ImageView) findViewById(R.id.id_tab_personal_img);
        idTabMoreImg = (ImageView) findViewById(R.id.id_tab_more_img);
        idTabBorrowImg = (ImageView) findViewById(R.id.id_tab_borrow_img);
        tvHome = (TextView) findViewById(R.id.tv_home);
        tvTender = (TextView) findViewById(R.id.tv_tender);
        tvMine = (TextView) findViewById(R.id.tv_mine);
        tvMore = (TextView) findViewById(R.id.tv_more);
        tvBorrow = (TextView) findViewById(R.id.tv_borrow);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //程序关闭，用于推送判断
        ActivityManage.setRun(false);
    }

    //未锁屏时3分钟获取一次系统时间
//    private Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            if (!isBackstage) {
//                new ServiceTimeHelper(MainActivity.this).getTime();
//            }
//            handler.sendEmptyMessageDelayed(0, 4 * 60 * 1000);
//        }
//    };
}
